package org.example.demo;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.servlet.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final ObjectMapper M = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求数据：json的格式
        req.setCharacterEncoding("UTF-8");
        //反序列化：json字符串转Java对象
        User user = M.readValue(req.getInputStream(),User.class);
        //模拟验证账号密码
        //验证的结果，设置到一个对象中，再转换为json字符串并返回客户端
        Map<String,Object> map = new HashMap<>();
        //验证通过
        if("abc".equals(user.getUsername()) && "123".equals(user.getPassword())){
            map.put("ok",true);
            //创建session用户会话(本身是获取session，传入boolean=true，获取不到会创建一个)
            HttpSession session = req.getSession();//=getSession(true)
            //然后就可以使用session会话来保存一些用户信息
            session.setAttribute("user",user);
        //验证失败
        }else {
            map.put("ok",false);
            map.put("msg","账号或密码错误");
        }

        //返回响应，设置数据格式和编码
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(M.writeValueAsString(map));
    }
}
